package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContest;
import com.itheima.common.R;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: guozy
 * @Date: 2022/8/2 - 08 - 02 - 10:55
 * @Description: com.itheima.controller
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询当前用户的购物车信息
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看当前用户购物车信息");
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContest.getCurrentId());
        queryWrapper.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据:{}",shoppingCart);
        // 设置用户id,指定当前是哪个用户的购物车数据
        Long currentId = BaseContest.getCurrentId();
        shoppingCart.setUserId(currentId);
        // 通过dishId的值是否为空,来判断是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        if (dishId!=null){
            // 添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else {
            // 添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        // 查询当前菜品或者套餐是否在购物车中
        ShoppingCart serviceOne = shoppingCartService.getOne(queryWrapper);
        if (serviceOne!=null){
            //如果已经存在,在原来的数量基础加一
            Integer number = serviceOne.getNumber();
            serviceOne.setNumber(number+1);
            //保存修改
            shoppingCartService.updateById(serviceOne);
        }else {
            //如果不存在,则添加到购物车,数量默认就是一
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            serviceOne = shoppingCart;
        }
        return R.success(serviceOne);
    }

    /**
     * 清除购物车菜品
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> delectALL(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        //清除本人的购物车
        queryWrapper.eq(ShoppingCart::getUserId,BaseContest.getCurrentId());
        shoppingCartService.remove(queryWrapper);
        return R.success("清除成功");
    }
}
